<!--心率呼吸体动图-->
<template>
  <div id="heartRateChart" class="chart">
    <div class="title-div">
      <span class="title">心率呼吸体动图</span>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import {nextTick, onMounted, reactive, watch} from 'vue';
import moment from 'moment';
import * as echarts from 'echarts';

const state = reactive({
  sleepData: [] as any,
  startTime: null as any
})

// eslint-disable-next-line no-undef
const props = defineProps({
  sleepData: [] as any,
  startTime: null as any,
  sleepRefresh: {
    type: Number,
    default: 0
  }
});

onMounted(() => {
  if (props.sleepData.length > 0) {
    state.sleepData = props.sleepData
  }
  if (props.startTime) {
    state.startTime = props.startTime
  }
  nextTick(() => {
    init();
  })
});

watch(
    () => [props.sleepData, props.startTime, props.sleepRefresh],
    (newValue, oldValue) => {
      console.log('sleepRefresh', oldValue, newValue)
      if (!newValue[0] && !newValue[1]) {
        return
      }
      if (newValue[0]) {
        state.sleepData = newValue[0]
      }
      if (newValue[1]) {
        state.startTime = newValue[1]
      }
      nextTick(() => {
        init();
      })
    },
    {deep: true},
);
/**
 * 初始化函数
 * */
const init = async () => {
  if (!state.startTime || state.sleepData.length === 0) {
    return
  }
  let start = moment(state.startTime)
  let date = moment()
  //计算相差的天数
  const day = date.diff(start, 'days');
  if (day > 8) {
    return
  }
  let dataArr = state.sleepData;
  let mtHrCurve = [] as any; // 心率
  let mtBrCurves = [] as any; // 呼吸
  let mtMrCurve = [] as any; // 体动
  let outBedArray = [] as any;
  let mtHrCurveArr = [] as any;
  let mtBrCurvesArr = [] as any;
  let mtMrCurveArr = [] as any;

  let startTime = new Date();
  let endTime = new Date();
  if (dataArr.length > 0) {
    dataArr.forEach((_) => {
      if (startTime.getTime() > new Date(_.tSleepDate).getTime()) {
        startTime = new Date(_.tSleepDate);
      }
      if (endTime.getTime() < new Date(_.tWakeTime).getTime()) {
        endTime = new Date(_.tWakeTime);
      }
    });

    for (let i in dataArr) {
      let tStartSleep = dataArr[i].tStartSleep;
      // 心率
      let mtHrCurveArray = dataArr[i].mtHrCurve.split(',') as any;
      for (let k = 0; k < mtHrCurveArray.length; k++) {
        mtHrCurve.push({
          hr: parseInt(mtHrCurveArray[k]),
          time: new Date(tStartSleep).setSeconds(k * 30),
        });
      }
      // 呼吸
      let mtBrCurvesArray = dataArr[i].mtBrCurve.split(',');
      for (let k = 0; k < mtBrCurvesArray.length; k++) {
        mtBrCurves.push({
          br: parseInt(mtBrCurvesArray[k]),
          time: new Date(tStartSleep).setSeconds(k * 30),
        });
      }
      // 体动
      let mtMrCurveArray = dataArr[i].mtMrCurve.split(',');
      for (let k = 0; k < mtMrCurveArray.length; k++) {
        mtMrCurve.push({
          mr: parseInt(mtMrCurveArray[k]),
          time: new Date(tStartSleep).setSeconds(k * 30),
        });
      }
    }
  }
  // -----------------计算出相差多少小时----------------------
  let date3 = endTime.getTime() - startTime.getTime();
  console.log('-----', date3);
  let hours = Math.floor(date3 / (30 * 1000));
  let hoursArr = [] as any; // x轴上的数据
  let hrMax = 0 as any;
  let brMax = 0 as any;

  for (let i = 0; i < hours; i++) {
    let longTime = new Date(startTime).setSeconds(i * 30);
    const longTimeFormat = moment(longTime).format('YYYY/MM/DD hh:mm:ss');
    hoursArr.push(longTimeFormat);
    let hr = mtHrCurve.find((f: any) => f.time >= longTime && f.time < longTime + 30 && f.hr > 0) || {
      hr: null,
      time: 0,
    };
    hrMax = hr.hr > hrMax ? hr.hr : hrMax;
    mtHrCurveArr.push(hr ? hr.hr : null);
    let br = mtBrCurves.find((f: any) => f.time >= longTime && f.time < longTime + 30 && f.br > 0) || {
      br: null,
      time: 0,
    };
    brMax = br.br > brMax ? br.br : brMax;
    mtBrCurvesArr.push(br ? br.br : null);
    let mr = mtMrCurve.find((f: any) => f.time >= longTime && f.time < longTime + 30) || {
      mr: null,
      time: 0,
    };
    mtMrCurveArr.push(mr.mr ? mr.mr * 5 : null);
    outBedArray.push(hr.hr > 0 || br.br > 0 || mr.mr > 0 ? 0 : 10);
  }
  for (let n = outBedArray.length - 1; n >= 0; n--) {
    if (outBedArray[n] === 10) {
      outBedArray[n] = null;
    } else {
      break;
    }
  }
  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.init(document.getElementById('heartRateChart'));
  // eslint-disable-next-line no-unused-vars
  // 绘制图表
  myChart.setOption({
    title: {
      text: '心率呼吸体动图',
      subtext: '最多展示7天数据'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (dataArray: any) {
        // eslint-disable-next-line one-var
        let hr = '-' as any,
            br = '-' as any,
            mr = '-' as any,
            outBed = '-' as any,
            time = '-' as any;
        if (dataArray) {
          time =
              dataArray[0] && dataArray[0].axisValue
                  ? dataArray[0].axisValue.replace('\n', ' ')
                  : '-';
          hr = dataArray[0] && dataArray[0].data ? parseInt(dataArray[0].data) : '-';
          br = dataArray[1] && dataArray[1].data ? parseInt(dataArray[1].data) : '-';
          mr = dataArray[2] && dataArray[2].data ? '是' : '否';
          outBed = dataArray[3] && dataArray[3].data === 0 ? '否' : '是';
        }
        return (
            '时间：' +
            time +
            '<br/>' +
            '心率：' +
            hr +
            '<br/>' +
            '呼吸：' +
            br +
            '<br/>' +
            '体动：' +
            mr +
            '<br/>离床：' +
            outBed
        );
      },
    },
    legend: {
      data: ['心率', '呼吸', '体动', '离床'],
    },
    grid: {
      y2: 80,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: {onZero: false},
      data: hoursArr.map(function (str: any) {
        return str.replace(' ', '\n');
      }),
      axisLabel: {
        interval: hoursArr.length / 50,
        rotate: 40,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '心率(次/每分)',
        min: 1,
        max: parseInt(hrMax),
        axisLabel: {
          formatter: '{value} ',
        },
      },
      {
        type: 'value',
        name: '呼吸(次/每分)',
        min: 1,
        max: parseInt(brMax),
        axisLabel: {
          formatter: '{value} ',
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 20,
        zoomLock: true,
      },
      {
        start: 0,
        end: 20,
        zoomLock: true,
      },
    ],
    series: [
      {
        name: '心率',
        type: 'line',
        smooth: true,
        data: mtHrCurveArr,
        color: ['#DB9B5C'],
        markLine: {
          data: [
            {type: 'max', name: '最大值'},
            {type: 'max', name: '最大值'},
            {type: 'min', name: '最小值'}],
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(191,91,22,0.8)',
            },
            {
              offset: 1,
              color: 'rgba(255,229,212,0.3)',
            },
          ]),
        },
      },
      {
        name: '呼吸',
        type: 'line',
        smooth: true,
        data: mtBrCurvesArr,
        color: ['#E062AE'],
        markLine: {
          data: [
            {type: 'max', name: '最大值'},
            {type: 'max', name: '最大值'},
            {type: 'min', name: '最小值'}],
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(122,41,123,0.8)',
            },
            {
              offset: 1,
              color: 'rgba(237,211,237,0.3)',
            },
          ]),
        },
      },
      {
        name: '体动',
        type: 'line',
        data: mtMrCurveArr,
        color: ['#FF0000'],
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(0,122,174,0.8)',
            },
            {
              offset: 1,
              color: 'rgba(200,235,250,0.3)',
            },
          ]),
        },
      },
      {
        name: '离床',
        type: 'line',
        data: outBedArray,
        color: ['#5384FB'],
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(0,122,174,0.8)',
            },
            {
              offset: 1,
              color: 'rgba(200,235,250,0.3)',
            },
          ]),
        },
      },
    ],
  });
};
</script>

<style lang="less" scoped>
.chart {
  position: relative;
  border: 1px solid rgba(198, 202, 209, 0.5);
  border-radius: 8px;
  padding: 70px 20px 20px 20px;
  height: 420px;

  .title-div {
    position: absolute;
    top: 10px;
    left: 20px;
    display: flex;

    .title {
      font-weight: bold;
      color: rgba(0, 0, 0, 0.6);
      margin-bottom: 10px;
    }

    .unit {
      color: #8b96a6;
      font-size: 12px;
    }
  }
}
</style>
